package com.scjp_Java6.ExceptionHandling;

import java.io.*;
import java.util.Vector;

public class ListOfNumbers {
	private Vector<Integer> victor;
	private static final int SIZE = 10;

	public ListOfNumbers() {
		victor = new Vector<Integer>(SIZE);
		for (int i = 0; i < SIZE; i++)
			victor.addElement(new Integer(i));
	}

	public void readList() {
		// try {
		//
		// File file = new File("InFile.txt");
		//
		// if (file.createNewFile()) {
		// System.out.println("File is created!");
		// } else {
		// System.out.println("File already exists.");
		// }
		//
		// } catch (IOException e) {
		// e.printStackTrace();
		// }
		// read
		try {
			// Open the file that is the first
			// command line parameter
			FileInputStream fstream = new FileInputStream("InFile.txt");
			// Get the object of DataInputStream
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;
			// Read File Line By Line
			while ((strLine = br.readLine()) != null) {
				// Print the content on the console
				System.out.println(strLine);
				victor.add(Integer.parseInt(strLine));
			}
			// Close the input stream
			in.close();

			// System.out.println("\n\nNew values: ");
			// for (int i=0; i<victor.size(); i++) {
			// System.out.println(victor.get(i));
			// }
		} catch (Exception e) {// Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}
	}

	public void writeList() {
		PrintWriter out = null;

		try {
			System.out.println("Entering try statement");
			out = new PrintWriter(new FileWriter("OutFile.txt"));

			for (int i = 0; i < victor.size(); i++) {
				out.println("Value at: " + i + " = " + victor.elementAt(i));
			}
		} catch (ArrayIndexOutOfBoundsException e) {
			System.err.println("Caught ArrayIndexOutOfBoundsException: "
					+ e.getMessage());
		} catch (IOException e) {
			System.err.println("Caught IOException: " + e.getMessage());
		} finally {
			if (out != null) {
				System.out.println("Closing PrintWriter");
				out.close();
			} else {
				System.out.println("PrintWriter not open");
			}
		}
	}
}